package com.quectel.taskserver.mock.job;

import cn.hutool.core.lang.func.LambdaUtil;
import com.alibaba.cloud.commons.lang.StringUtils;
import com.quectel.constant.core.device.DeviceCategoryCodeConstants;
import com.quectel.core.module.ai.dto.mongo.MongoAiEventRecordDto;
import com.quectel.core.module.ai.service.mongo.MongoAiEventRecordService;
import com.quectel.core.module.device.dto.DeviceDto;
import com.quectel.core.module.device.service.DeviceService;
import com.quectel.core.module.village.dto.VillageDto;
import com.quectel.core.module.village.service.VillageService;
import com.quectel.taskserver.mock.MockLimit;
import com.quectel.util.common.JacksonUtils;
import com.quectel.util.kit.StorageKit;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.shardingsphere.elasticjob.api.ShardingContext;
import org.apache.shardingsphere.elasticjob.simple.job.SimpleJob;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.security.SecureRandom;
import java.util.*;

/**
 * @author rananxin
 * @email ryan.ran@quectel.com
 * @date 2022/4/14 2:48 下午
 */
@Component
@Slf4j
public class AiEventRecordMockTask implements SimpleJob {
    /**
     * 区域入侵照片集
     */
    private final List<String> REGIONAL_INVASION_PIC_SET =
            new ArrayList<>(Arrays.asList("7e21c483078a4a6ca268e45d31719ec6.png"
                    , "1449534877f14746b28f86f4b93c10dd.png"));
    /**
     * 车牌抓拍照片集
     */
    private final List<String> LICENSE_PLATE_CAPTURE_PIC_SET =
            new ArrayList<>(Arrays.asList("f5b58cad06f440229304e93f8e3bb8cc.jpg"
                    , "96d3d81d1c2a4127a5e84680ba44758a.png"));
    /**
     * 人脸抓拍照片集
     */
    private final List<String> FACE_CAPTURE_PIC_SET =
            new ArrayList<>(Arrays.asList("52ab5ee567544d8d881e8101ee16acab.png"
                    , "ce57075435f040119ee696cdfe7c17c3.jpeg"));

    /**
     * 高空抛物照片集
     */
    private final List<String> HIGH_TOSS_CAPTURE_PIC_SET =
            new ArrayList<>(Arrays.asList("a94325e0d8c1461aaf9df138b9278426.png"
                    , "ad5dddb5b9164d40bcb04d727a4cbb00.png"));

    /**
     * 电梯预警照片集
     */
    private final List<String> ELEVATOR_WARNING_CAPTURE_PIC_SET =
            new ArrayList<>(Arrays.asList("a4494ce5b51948dbb7be6de110d3b0ff.png"
                    , "a5acaa855d5f4a5186dd793152ac3233.png"
                    , "5a7c122897744633ae20750273202676.png"));

    @DubboReference
    private DeviceService deviceService;
    @DubboReference
    private MongoAiEventRecordService aiEventRecordService;

    @DubboReference
    private VillageService villageService;

    @Override
    public void execute(ShardingContext shardingContext) {
        exec();
    }

    private void exec() {

        if (!MockLimit.enableMock() || MockLimit.mockVillageCodes() == null) {
            return;
        }
        for (String villageCode : MockLimit.mockVillageCodes()) {
            VillageDto villageDto = villageService.selectByCode(villageCode);
            if (villageDto == null) {
                continue;
            }
            long currentTimeMillis = System.currentTimeMillis();

            Map<String, Object> params = new HashMap<>();
            params.put("deviceCategoryCode", DeviceCategoryCodeConstants.INTELLIGENT_MONITOR);
            params.put(LambdaUtil.getFieldName(DeviceDto::getVillageId), villageDto.getId());
            List<DeviceDto> deviceDtos = deviceService.queryList(params);

            if (deviceDtos != null && !deviceDtos.isEmpty()) {
                SecureRandom secureRandom = new SecureRandom();
                int deviceIndex = secureRandom.nextInt(deviceDtos.size());
                int typeIndex = secureRandom.nextInt(7) + 1;
                String img = "";
                switch (typeIndex) {
                    case 1:
                        if (!REGIONAL_INVASION_PIC_SET.isEmpty()) {
                            img = REGIONAL_INVASION_PIC_SET.get(secureRandom.nextInt(REGIONAL_INVASION_PIC_SET.size()));
                        }
                        break;
                    case 2:
                        if (!LICENSE_PLATE_CAPTURE_PIC_SET.isEmpty()) {
                            img = LICENSE_PLATE_CAPTURE_PIC_SET.get(secureRandom.nextInt(LICENSE_PLATE_CAPTURE_PIC_SET.size()));
                        }
                        break;
                    case 3:
                        if (!FACE_CAPTURE_PIC_SET.isEmpty()) {
                            img = FACE_CAPTURE_PIC_SET.get(secureRandom.nextInt(FACE_CAPTURE_PIC_SET.size()));
                        }
                        break;
                    case 6:
                        if (!HIGH_TOSS_CAPTURE_PIC_SET.isEmpty()) {
                            img = HIGH_TOSS_CAPTURE_PIC_SET.get(secureRandom.nextInt(HIGH_TOSS_CAPTURE_PIC_SET.size()));
                        }
                        break;
                    case 7:
                        if (!ELEVATOR_WARNING_CAPTURE_PIC_SET.isEmpty()) {
                            img = ELEVATOR_WARNING_CAPTURE_PIC_SET.get(secureRandom.nextInt(ELEVATOR_WARNING_CAPTURE_PIC_SET.size()));
                        }
                        break;
                    default:
                        log.warn("Unexpected value: {}", typeIndex);
                }

                if (StringUtils.isNotBlank(img)) {
                    DeviceDto deviceDto = deviceDtos.get(deviceIndex);
                    MongoAiEventRecordDto aiEventRecordDto = new MongoAiEventRecordDto();
                    aiEventRecordDto.setTenantId(deviceDto.getTenantId());
                    aiEventRecordDto.setVillageId(deviceDto.getVillageId());
                    aiEventRecordDto.setDeviceCategoryId(deviceDto.getDeviceCategoryId());
                    aiEventRecordDto.setDeviceTypeId(deviceDto.getDeviceTypeId());
                    aiEventRecordDto.setDeviceId(deviceDto.getId());
                    aiEventRecordDto.setDeviceName(deviceDto.getName());
                    aiEventRecordDto.setEventType((byte) typeIndex);

                    try (InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("mock/" + img)) {
                        if (resourceAsStream != null) {
                            aiEventRecordDto.setSnapImages(JacksonUtils.toJsonString(Arrays.asList(
                                    StorageKit.uploadStreamToPublicBucketObtainUrl(resourceAsStream, img)
                            )));
                        }

                    } catch (Exception e) {
                        log.error("上传图片出错");
                    }

                    aiEventRecordDto.setEventTime(new Date(currentTimeMillis - secureRandom.nextInt(2 * 60 * 1000)));
                    aiEventRecordDto.setRecordTime(new Date(currentTimeMillis - secureRandom.nextInt(2 * 60 * 1000)));
                    aiEventRecordDto.setLongitude(deviceDto.getLongitude());
                    aiEventRecordDto.setLatitude(deviceDto.getLatitude());
                    aiEventRecordService.save(aiEventRecordDto);
                }
            }
        }
    }

}
